﻿using System.Collections.Generic;
using System.Windows.Media;
using System.Windows.Controls;

using MSAP.Framework.Interfaces;
using MSAP.Framework.Controls;
using System.Windows.Input;
using System.Security.Principal;

namespace MSAP.Framework
{
    public class ShellBase : ModuleBase, IShell
    {
        protected ShellBase(string id, string title, string comments, ImageSource icon)
            : base(id, title, comments, icon)
        {
        }
        
        #region ----------------- Impementation de IShell -----------------
        public void Init()
        {
            Init(this);

            if (AuthentifyUser() == true)
            {
                m_Modules = new List<IModule>();
                IsEnabled = true;
            }
            else
            {
                IsEnabled = false;
            }
        }

        public void AddModule(IModule module)
        {
            Modules.Add(module);
        }

        public IModule GetModule(string id)
        {
            if (m_Modules == null || m_Modules.Count == 0)
            {
                return null;
            }
            return m_Modules.Find(delegate(IModule match) { return (match.ID == id); });
        }

        public TabControl View
        {
            get
            {
                return m_WorkplacesView as TabControl;
            }
            set
            {
                m_WorkplacesView = value as AnimatedTabControl;
                if (m_WorkplacesView != null && m_WorkplacesView.Items.Count == 0 && m_Workplaces.Count > 0)
                {
                    foreach (IServicePage service in m_Workplaces)
                        AddWorkplaceView(service);
                }
                if (value != null)
                {
                    m_WorkplacesView.CloseAllCommand = CloseAllViewCommand;
                }
            }
        }

        public IServicePage DefaultServicePage
        {
            get
            {
                return m_DefaultServicePage;
            }
            set
            {
                // On met à false IsDefault si le DefaultServicePage change.
                if (m_DefaultServicePage != null && DefaultServicePage != value && m_DefaultServicePage.View != null)
                {
                    AnimatedTabItem item = m_DefaultServicePage.View as AnimatedTabItem;
                    item.IsDefault = false;
                }
                m_DefaultServicePage = value;
                if (m_DefaultServicePage != null && m_DefaultServicePage.View != null)
                {
                    AnimatedTabItem item = m_DefaultServicePage.View as AnimatedTabItem;
                    item.IsDefault = true;
                }
            }
        }

        public List<IModule> Modules
        {
            get
            {
                return m_Modules;
            }
        }

        public IServicePage CurrentServicePage
        {
            get
            {
                AnimatedTabItem item = m_WorkplacesView.SelectedItem as AnimatedTabItem;
                if (item != null)
                    return item.DataContext as IServicePage;
                return null;
            }
        }

        public TabItem CurrentServicePageView
        {
            get
            {
                return m_WorkplacesView.SelectedItem as TabItem;
            }
        }
        public string LoginName
        {
            get
            {
                if (m_LoginName == null)
                {
                    m_LoginName = WindowsIdentity.GetCurrent().Name.ToUpper();
                    if (m_LoginName.LastIndexOf('\\') != -1)
                        m_LoginName = m_LoginName.Substring(m_LoginName.LastIndexOf('\\') + 1);
                }
                return m_LoginName;
            }
        }

        public virtual string UserName
        {
            get
            {
                // $$$ TODO votre nom d'utilisateur sympa
                return LoginName;
            }
        }
        /// <summary>
        /// Retourne le role le plus fort de l'utilisateur 
        /// </summary>
        public virtual string UserRole
        {
            get
            {
                // $$$ TODO votre role d'utilisateur 
                return "Role";
            }
        }
        /// <summary>
        /// Retourne le role le plus fort de l'utilisateur sous forme lisible dans l'ihm
        /// </summary>
        public virtual string UserRoleFrendly
        {
            get
            {
                // $$$ TODO votre role d'utilisateur 
                return "Role";
            }
        }

        public eLoginStatus LoginStatus 
        { 
            get 
            {
                return m_LoginStatus;
            }        
        }

        #endregion ----------------- Impementation de IShell -----------------

        #region ------ Implementation de IModule ------
        public void AddServicePage(IServicePage service)
        {
            ServicePages.Add(service);
            if (View != null)
            {
                AddWorkplaceView(service);
            }
        }
        
        public void MoveToServicePage(IServicePage service)
        {
            MoveToWorkplaceView(service);
        }
        
        public void RemoveServicePage(IServicePage service)
        {
            if (DefaultServicePage != null && service == DefaultServicePage)
            {
                return;
            }
            if (ServicePages.Contains(service) == true)
            {
                ServicePages.Remove(service);
                if (View != null)
                {
                    RemoveWorkplaceView(service);
                }
                service = null;
            }
        }

        public bool CanRemoveServicePage(IServicePage service)
        {
            if (DefaultServicePage != null && service == DefaultServicePage)
            {
                return false;
            }
            return true;
        }

        public void RemoveAllServicePage()
        {
            int countWorkplaces = ServicePages.Count;
            for (int i = countWorkplaces - 1; i >= 0; i--)
            {
                if (ServicePages[i].CloseViewCommand.CanExecute(null) == true)
                    ServicePages[i].CloseViewCommand.Execute(null);
            }
        }
        #endregion ------ Implementation de IModule ------
        
        public bool IsEnabled
        {
            get
            {
                return m_IsEnabled;
            }
            set
            {
                if (value.Equals(m_IsEnabled) == false)
                {
                    m_IsEnabled = value;
                    RaisePropertyChanged("IsEnabled");
                }
            }
        }

        private void AddWorkplaceView(IServicePage service)
        {
            Frame frame = new Frame();
            frame.Source = service.ServiceUri;
            frame.DataContext = service;

            AnimatedTabItem view = new AnimatedTabItem();

            view.DataContext = service;
            view.Header = service.Title;
            view.Content = frame;

            if (DefaultServicePage != null && DefaultServicePage == service)
                view.IsDefault = true;

            service.View = view;

            //m_WorkplacesView.BeginInit();
            m_WorkplacesView.Items.Add(service.View);
            m_WorkplacesView.SelectedItem = service.View;
            //m_WorkplacesView.EndInit();


            if (m_WorkplacesView.Items.Count > 2)
            {
                m_WorkplacesView.HasMoreThanTwoItems = true;
            }

        }

        private void RemoveWorkplaceView(IServicePage service)
        {
            m_WorkplacesView.Items.Remove(service.View);
            if (m_WorkplacesView.Items.Count > 2)
            {
                m_WorkplacesView.HasMoreThanTwoItems = true;
            }
            else
            {
                m_WorkplacesView.HasMoreThanTwoItems = false;
            }
        }

        private ICommand CloseAllViewCommand
        {
            get
            {
                if (m_CloseAllViewCommand == null)
                {
                    m_CloseAllViewCommand = new RelayCommand(Execute => CloseAllView(), CanExecute => CanCloseAllView());
                }
                return m_CloseAllViewCommand;
            }
        }

        private void CloseAllView()
        {
            RemoveAllServicePage();
        }

        private bool CanCloseAllView()
        {
            return true;
        }

        private void MoveToWorkplaceView(IServicePage service)
        {
            m_WorkplacesView.SelectedItem = service.View;
        }

        private bool AuthentifyUser()
        {
            try
            {
                // $$$ TODO your Authentify action
                m_LoginStatus = eLoginStatus.Connected;
                return true;
            }
            catch
            {
                m_LoginStatus = eLoginStatus.Refused;
                return false;
            }
            finally
            {
                RaisePropertyChanged("LoginStatus");
                RaisePropertyChanged("LoginName");
                RaisePropertyChanged("ConnectedUser");
                RaisePropertyChanged("UserName");
                RaisePropertyChanged("UserRole");
            }
        }

        #region ---- private Fields ------
        protected IServicePage m_DefaultServicePage;
        protected AnimatedTabControl m_WorkplacesView;
        protected ICommand m_CloseAllViewCommand;
        protected string m_LoginName;
        protected List<IModule> m_Modules;
        protected eLoginStatus m_LoginStatus;
        protected bool m_IsEnabled;
        #endregion ---- Fields ------

    }
}
